package com.asiainfo.dacp.datastash.broker.flow.core.domain;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.curator.shaded.com.google.common.collect.Lists;

import com.asiainfo.dacp.datastash.broker.common.constant.ZKConstant;
import com.asiainfo.dacp.datastash.broker.common.enums.UnitStateEnum;
import com.asiainfo.dacp.datastash.broker.core.enums.UnitTaskStateEnum;
import com.asiainfo.dacp.datastash.broker.core.vo.StashUnitTask;
import com.asiainfo.dacp.datastash.broker.tracelog.StashTraceLogVo;
import com.asiainfo.dacp.datastash.domain.unit.models.DataStashUnit;
import com.asiainfo.dacp.util.SimpleKey;

import lombok.Data;

@Data
public class Flow {

	private String serNo = SimpleKey.genUuid(32);
	private String unitCode;
	private String batchNo;
	
	private UnitStateEnum unitState;
	
	private String remark;
	
	private DataStashUnit unit;
	
	private int taskCnt;
	
	private int taskOKCnt;
	
	private int taskRunnableCnt;
	
	private Map<String, StashUnitTask> tasks;
	
	public StashUnitTask getTask(String taskSerNo){
		return tasks.get(taskSerNo);
	}
	
	public Flow(DataStashUnit unit){
		this.unit = unit;
		this.batchNo = unit.getBatchNo();
		this.unitCode = unit.getUnitCode();
		this.unitState = UnitStateEnum.INIT;
	}
	
	public String buildSerNo(){
		return String.format("%s-%s", this.getUnitCode(), this.getSerNo());
	}  
	
	
	public List<StashUnitTask> getReadyTasks(){
		Collection<StashUnitTask> values = tasks.values();

		for(StashUnitTask task: values){
			if(task.getTaskState() == UnitTaskStateEnum.INIT){
				task.setTaskState(UnitTaskStateEnum.BLOCKED_RELAY);
			}
		}
		List<StashUnitTask> rstTasks = Lists.newArrayList();
		if(tasks != null && tasks.size() >0){
			for(StashUnitTask task: values){
				if(task.getTaskState() == UnitTaskStateEnum.BLOCKED_RELAY){
					List<String> relayTaskIds = task.getPreTaskProcIds();
					if (relayTaskIds != null && relayTaskIds.size() > 0) {
						boolean ok = true;
						for (String relayTaskId : relayTaskIds) {
							StashUnitTask preTask = tasks.get(relayTaskId);
							if(preTask.getTaskState() != UnitTaskStateEnum.SUCESS){
								ok = false;
							} 
						}
						if(!ok) continue;
					}
					rstTasks.add(task);
				} 
			}
		}
		this.taskRunnableCnt = rstTasks.size();
		return rstTasks;
	}
}
